package com.iretailer.report.analyze.device.fieAnalysis.device;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iretailer.report.analyze.annotation.AnalyzeClass;
import com.iretailer.report.analyze.commonModel.WifiFormat;
import com.iretailer.report.analyze.commonModel.WifiProperties;
import com.iretailer.report.analyze.commonUtil.ResponeResultType;
import com.iretailer.report.analyze.device.fieAnalysis.FileAnalyze;
import com.iretailer.report.util.StringUtil;
import com.iretailer.report.util.TimeUtilOld;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.handler.codec.http.multipart.FileUpload;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.MixedAttribute;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.zip.GZIPInputStream;

/**
 * @Auther: xjw
 * @Date: 2019/3/10 18:53
 * @Description:
 */
@AnalyzeClass
@Component
public class BksWifi extends FileAnalyze {

    @Value("${netty.path.bkswifi}")
    private String bkswifi;

    private static final Logger log = LoggerFactory.getLogger(BksWifi.class);

    @Override
    public String[] analyzePath() {
        if (StringUtil.notEmpty(bkswifi)) {
            return bkswifi.split(",");
        } else {
            return new String[]{"/bkswifi"};
        }
    }

    @Override
    public ResponeResultType fileInsert(Map<String, Object> paramsMap, HttpPostRequestDecoder decoder) {
        Map<String, Object> contentMap = transform2Map(decoder);
        boolean result = false;
        if (!contentMap.isEmpty()) {
            String ip = (String) paramsMap.get("remoreAddr");
            String mac = (String) paramsMap.get("s_mac");
            String deviceId = mac.replaceAll(":", "").toLowerCase();
            JSONObject data = (JSONObject) contentMap.get("data");
            JSONArray tracks = (JSONArray) data.get("tracks");
            WifiFormat wifiFormat = new WifiFormat();
            wifiFormat.setIpAddr(ip);
            wifiFormat.setMacAddr(mac);
            if (tracks != null && tracks.size() > 0) {
                List<WifiProperties> ps = new ArrayList<>();
                wifiFormat.setPerperties(ps);
                for (int i = 0, len = tracks.size(); i < len; i++) {
                    WifiProperties p = new WifiProperties();
                    JSONObject track = (JSONObject) tracks.get(i);
                    Long t = Long.parseLong((String) track.get("t"));
                    Date date = new Date(t * 1000);
                    p.setDate(TimeUtilOld.getDate(date));
                    p.setDeviceId(deviceId);
                    p.setMacAddress(((String) track.get("m")).replaceAll(":", ""));
                    p.setDateTime(TimeUtilOld.getDateTime(date));
                    p.setRssi(Integer.parseInt((String) track.get("r")));
                    ps.add(p);
                }

            }

//            result = insertWifi(wifiFormat);
        }
        if (result) {
            return ResponeResultType.getOkRequest(ResponeResultType.CFLType.CLOSE_ON_FAILURE);
        } else {
            return ResponeResultType.getBadRequest(ResponeResultType.CFLType.CLOSE_ON_FAILURE);
        }
    }

    private Map<String, Object> transform2Map(HttpPostRequestDecoder decoder) {
        Map<String, Object> itemMap = new HashMap<>();
        while (decoder.hasNext()) {
            InterfaceHttpData data = decoder.next();
            if (data != null) {
                try {
                    String name = data.getName();
                    InterfaceHttpData.HttpDataType dataType = data.getHttpDataType();
                    switch (dataType) {
                        case Attribute:
                            itemMap.put(name, ((MixedAttribute) data).getByteBuf().toString(CharsetUtil.UTF_8));
                            break;
                        case FileUpload:
                            ByteBuf byteBuf = ((FileUpload) data).getByteBuf();
                            ByteBufInputStream bbis = new ByteBufInputStream(byteBuf);
                            itemMap.put(name, gzip2String(bbis));
                            break;
                    }
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                } finally {
                    data.release();
                }
            }
        }
        return itemMap;
    }

    /**
     * InputStream 中带有 GZIP 压缩
     *
     * @return
     */
    private static JSONObject gzip2String(InputStream inputStream) {
        try (GZIPInputStream gis = new GZIPInputStream(inputStream)) {
            StringBuilder result = new StringBuilder();
            int count;
            byte data[] = new byte[1024];
            while ((count = gis.read(data, 0, 1024)) != -1) {
                result.append(new String(data, 0, count));
            }
            return JSON.parseObject(result.toString());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


}
